package com.mai4j.maiadmin.support.web.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
public class CookieUtil {

    /**
     * 添加cookie
     *
     * @param name  name
     * @param value value
     */
    public static void addCookie(String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setHttpOnly(true);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null && requestAttributes.getResponse() != null) {
            requestAttributes.getResponse().addCookie(cookie);
        }
    }

    /**
     * 获取Cookie值
     *
     * @param name name
     * @return value
     */
    public static String getValue(String name) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            Cookie cookie = WebUtils.getCookie(requestAttributes.getRequest(), name);
            return cookie != null ? cookie.getValue() : "";
        }
        return "";
    }
}
